﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Pvf.Core.Contents
{
    public sealed class PvfNStringContent : PvfContent<Dictionary<string, string>>
    {
        private Dictionary<string, string> _table;

        public override Dictionary<string, string> Data => _table;

        public override bool Load(Encoding encoding, IPvfModule module)
        {
            if (_table != null)
            {
                return true;
            }
            if (!base.Load(encoding, module))
            {
                return false;
            }

            _table = new Dictionary<string, string>();

            var data = BytesData;

            using (var ms = new MemoryStream(data))
            {
                using (var reader = new BinaryReader(ms))
                {
                    var sf = reader.ReadUInt16();
                    if (sf != Index.Env.NStringEntryKey)
                    {
                        throw new NotSupportedException("nstring.list数据校验异常");
                    }
                    reader.BaseStream.Position += 6;
                    var stringTableKey = reader.ReadInt32();

                    if (Index.Env.StringTable.TryGetValue(stringTableKey, out var foundValue))
                    {
                        var foundIndex = Index.Env.FindIndex(foundValue);
                        if (foundIndex != null)
                        {
                            var dictData = foundIndex.GetContent<PvfDictContent>().Data;
                            foreach (var dictItem in dictData)
                            {
                                _table.Add(dictItem.Key, dictItem.Value);
                            }
                        }
                    }

                    return true;
                }
            }
        }
    }
}
